// components/hxn-cart-item/index.js
let common_js = require("../../utils/common.js");

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    item: {
      type: Object,
      value: null
    }
  },


  observers: {
    'item': function (item) {
      //如果需要开启定时器
      if (item) {
        // 初始化数据
        this.initData(item);
        // 开启倒计时
        if (item.type == 2 || item.type == 3) {
          this.initTimerObj(item);
        }
      } else {
        this.clearTimer();
      }
    }
  },

  // 页面生命周期
  lifetimes: {
    // 页面销毁
    detached() {
      this.clearTimer();
    },
  },


  /**
   * 组件的初始数据
   */
  data: {
    timerObj: {
      timerId: null,
      isEnd: false,
      endTime: '',
      item: null
    },
    promotionPrice: '', //促销价格
    price: '', //原价
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //初始化数据
    initData: function (item) {
      let tmpPromotionPrice = '';
      let tmpPrice = '';

      if (item.type == 0) {
        //只有原价
        tmpPromotionPrice = item.price;
        tmpPrice = item.crossedPrice;
      } else {
        //促销或者团购的话有原价和促销价
        tmpPromotionPrice = item.promotionPrice;
        tmpPrice = item.price;
      }
      let percent = (item.process * 100).toFixed(2);
      this.setData({
        promotionPrice: tmpPromotionPrice,
        price: tmpPrice,
        precent: percent
      });
    },
    // 初始化
    initTimerObj(item) {
      if (!item.expire || item.expire <= 0) return;
      let tmpTimerObj = this.data.timerObj;
      if (item.expire > 0) {
        tmpTimerObj.endTime = new Date().getTime() + item.expire * 1000;
      }
      //set dasta
      this.setData({
        timerObj: tmpTimerObj
      });
      // 开启计时器
      this.countDownTimer();
    },
    // 计时器**********
    countDownTimer() { //倒计时函数
      // 获取当前时间，同时得到活动结束时间数组
      let newTime = new Date().getTime();
      let tmpTimerObj = this.data.timerObj;
      let endTime = tmpTimerObj.endTime;
      let time = (endTime - newTime) / 1000;
      // 如果活动未结束，对时间进行处理
      let hmsObj = common_js.getHrMinSecBySecond(time);
      tmpTimerObj.item = hmsObj.item;
      tmpTimerObj.isEnd = hmsObj.isEnd;
      // 先清除计时器
      this.clearTimer();
      //1s调用一次
      let that = this;
      let timerId = setTimeout(function () {
        that.countDownTimer();
      }, 1000);
      tmpTimerObj.timerId = timerId;
      // 渲染，然后每隔一秒执行一次倒计时函数
      this.setData({
        timerObj: tmpTimerObj
      })
      // 清除
      if (tmpTimerObj.isEnd) {
        this.clearTimer();
      }
    },
    // 清除计时器
    clearTimer() {
      if (this.data.timerObj.timerId) {
        clearTimeout(this.data.timerObj.timerId);
        this.data.timerObj.timerId = null;
      }
    },
    onMinus: function () {
      this.triggerEvent('minus', null, {});
    },
    onAdd: function () {
      this.triggerEvent('add', null, {});
    },
    onDelete: function () {
      this.triggerEvent('delete', null, {});
    }
  }
})